# -*- coding: utf-8 -*-
import hashlib
import json

import requests
from django.conf import settings

from async import async_job
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://p.51paypay.net/api/v1/pay/submit'
_QUERY_GATEWAY = 'http://p.51paypay.net/api/v1/pay/query'

APP_CONF = {
    '100010': {
        'API_KEY': '15552feac3981bde6cd870a0f4003db9'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('signature')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("boeingpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    key = _get_api_key(app_id)
    p_dict = {
        'amount': str(pay_amount),
        'appid': app_id,
        'subject': 'pay',
        'orderid': str(pay.id),
        'payType': '23',
        'notifyUrl': '{}/pay/api/{}/boeingpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id),
        'orderInfo': 'pay',
    }
    p_dict['signature'] = generate_sign(p_dict, key)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_GATEWAY, data=json.dumps(p_dict), headers=headers, timeout=3)
    _LOGGER.info("boeingpay data response: %s", response.text)
    return {'charge_info': json.loads(response.text)['data']['pay_url']}


def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    # data = dict(request.POST.iteritems())
    # _LOGGER.info("boeingpay notify data: %s", data)
    _LOGGER.info("boeingpay notify body: %s", request.body)
    data = json.loads(request.body)
    verify_notify_sign(data, key)
    pay_id = data['orderid']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('boeingpay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['status'])
    trade_no = ''
    total_fee = float(data['amount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 2:
        _LOGGER.info('boeingpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'orderid': str(pay_id),
        'appid': app_id,
    }
    p_dict['signature'] = generate_sign(p_dict, key)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_QUERY_GATEWAY, data=json.dumps(p_dict), headers=headers, timeout=10)
    _LOGGER.info(u'boeingpay query: %s', response.text)
    data = json.loads(response.text)['data']
    if response.status_code == 200:
        trade_status = int(data['pay_status'])
        total_fee = float(data['amount'])
        trade_no = ''
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 2:
            _LOGGER.info('boeingpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            if res:
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('boeingpay data error, status_code: %s', response.status_code)


if __name__ == '__main__':
    # p_dict = {
    #     'amount': '1.00',
    #     'appid': '100010',
    #     'subject': 'pay',
    #     'orderid': '123123121321',
    #     'payType': '23',
    #     'notifyUrl': 'http://www.baidu.com',
    #     'orderInfo': 'pay',
    # }
    # p_dict['signature'] = generate_sign(p_dict, '15552feac3981bde6cd870a0f4003db9')
    # j = json.dumps(p_dict, sort_keys=True)
    # headers = {'Content-Type': 'application/json;charset=utf-8'}
    # response = requests.post(_GATEWAY, data=j, headers=headers, timeout=3)
    # print response.text
    # print  response.url

    # headers = {
    #     "Content-Type": "application/json;charset=utf-8"
    # }
    # d = requests.post(_GATEWAY, data=json.dumps(p_dict), headers=headers, timeout=10)
    # print d.text
    # print d.url

    p_dict = {
        'orderid': '123123121321',
        'appid': '100010',
    }
    p_dict['signature'] = generate_sign(p_dict, '15552feac3981bde6cd870a0f4003db9')
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_QUERY_GATEWAY, data=json.dumps(p_dict), headers=headers, timeout=10)
    print response.text
